package cn.dakaqi.sys.topic.services;

import cn.dakaqi.entities.IndexData;
import cn.dakaqi.entities.SysTopic;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.Identities;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chunyang on 2016/4/21.
 */
@Component(value = "sysTopicService")
@Transactional
public class SysTopicServiceImpl implements SysTopicService
{
    @Autowired
    SysTopicDao sysTopicDao;
    @Autowired
    IndexDataService indexDataService;

    @Override
    public void create(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String code = Identities.randomBase62(10);//编码
        String title = jsonObject.getString("title");//标题
        String intro = jsonObject.getString("intro");//简介
        String background = jsonObject.getString("background");//背景图
        String promulgator = jsonObject.getString("promulgator");//发布人
        String tags = jsonObject.getString("tags");//本话题对应该的标签
        SysTopic sysTopic = new SysTopic();
        sysTopic.setCreateTime(Clock.DEFAULT.getCurrentDate());
        sysTopic.setTop(DKQConstant.TOP_NO);
        sysTopic.setDisplay(DKQConstant.DISPLAY_NO);
        sysTopic.setBackground(background);
        sysTopic.setIntro(intro);
        sysTopic.setTitle(title);
        sysTopic.setTags(tags);
        sysTopic.setPromulgator(promulgator);
        sysTopic.setCode(code);

        this.save(sysTopic);
    }

    @Override
    public void save(SysTopic sysTopic) throws ServiceRuntimeException
    {
        this.sysTopicDao.save(sysTopic);
        //将话题放入首页自定义的容器中
        IndexData indexData = new IndexData();
        indexData.setType("SysTopic");
        indexData.setCreateTime(Clock.DEFAULT.getCurrentDate());
        indexData.setDisplay(0);
        indexData.setSysTopic(sysTopic);
        indexData.setDelStatus(0);
        indexData.setTop(0);
        indexData.setStopStatus(0);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            indexData.setStopTime(formatter.parse(DateUtil.getAfterDate(7)));
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        this.indexDataService.save(indexData);

    }

    @Override
    public SysTopic findOne(Long id) throws ServiceRuntimeException
    {
        return this.sysTopicDao.findOne(id);
    }

    @Override
    public Page<SysTopic> findByDisplay(int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("display", new SearchFilter("display", SearchFilter.Operator.EQ, DKQConstant.DISPLAY_YES));
        Specification<SysTopic> spec = DynamicSpecifications.bySearchFilter(filters.values(), SysTopic.class);
        return this.sysTopicDao.findAll(spec, pageRequest);
    }

    @Override
    public Page<SysTopic> findByTop(String creatTime,int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("top", new SearchFilter("top", SearchFilter.Operator.EQ, DKQConstant.TOP_YES));
        if(StringUtils.isNotBlank(creatTime))
            filters.put("createTime", new SearchFilter("createTime", SearchFilter.Operator.GT, creatTime));
        Specification<SysTopic> spec = DynamicSpecifications.bySearchFilter(filters.values(), SysTopic.class);
        return this.sysTopicDao.findAll(spec,pageRequest);
    }

    @Override
    public List<SysTopic> findByTag(String createTime,String tags,int pageNumber) throws ServiceRuntimeException
    {
        List<SysTopic> result = new ArrayList<SysTopic>();
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");

        for(String tag:tags.split(";"))
        {
            Map<String,Object> map = new HashMap<String, Object>();
            //map.put("LIKE_NAME",name);
            //Map<String, SearchFilter> filters = SearchFilter.parse(map);

            Map<String, SearchFilter> filters = Maps.newHashMap();
            filters.put("tags", new SearchFilter("tags", SearchFilter.Operator.LIKE, tag));
            if(StringUtils.isNotBlank(createTime))
                filters.put("createTime", new SearchFilter("createTime", SearchFilter.Operator.GT, createTime));
            Specification<SysTopic> spec = DynamicSpecifications.bySearchFilter(filters.values(), SysTopic.class);
            List<SysTopic> temp = this.sysTopicDao.findAll(spec, sort);
            if(null != temp && temp.size()>0)
                result.addAll(temp);
        }
        List<SysTopic> listWithoutDup = new ArrayList<SysTopic>(new HashSet<SysTopic>(result));
        return listWithoutDup;
    }

    @Override
    public void display(String param)
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String code = jsonObject.getString("code");
        int status = jsonObject.getIntValue("status");
        this.updateDisplay(code,status);
    }

    @Override
    public void top(String param)
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String code = jsonObject.getString("code");
        int status = jsonObject.getIntValue("status");
        this.updateDisplay(code,status);
    }

    @Override
    public void updateDisplay(String code, int display) throws ServiceRuntimeException
    {
        SysTopic sysTopic = findByCode(code);
        if(null != sysTopic)
        {
            sysTopic.setDisplay(display);
            this.update(sysTopic);
        }
    }

    @Override
    public void udpateTop(String code, int top) throws ServiceRuntimeException
    {
        SysTopic sysTopic = findByCode(code);
        if(null != sysTopic)
        {
            sysTopic.setTop(top);
            this.update(sysTopic);
        }
    }

    @Override
    public SysTopic findByCode(String code) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("code", new SearchFilter("code", SearchFilter.Operator.EQ, code));
        Specification<SysTopic> spec = DynamicSpecifications.bySearchFilter(filters.values(), SysTopic.class);
        List<SysTopic> data = this.sysTopicDao.findAll(spec);
        if(null == data || data.size() == 0)
            return null;
        else
            return data.get(0);
    }

    @Override
    public void update(SysTopic sysTopice) throws ServiceRuntimeException
    {
        sysTopice.setCreateTime(Clock.DEFAULT.getCurrentDate());
        this.sysTopicDao.save(sysTopice);
    }

    @Override
    public SysTopic browse(String code)
    {
        SysTopic sysTopic = findByCode(code);
        if(null != sysTopic)
        {
            sysTopic.setBrowses(sysTopic.getBrowses()+1);
            this.update(sysTopic);
        }
        return sysTopic;
    }
    @Override
    public SysTopic browse(Long id)
    {
        SysTopic sysTopic = findOne(id);
        if(null != sysTopic)
        {
            sysTopic.setBrowses(sysTopic.getBrowses()+1);
            this.update(sysTopic);
        }
        return sysTopic;
    }
    @Override
    public void addGood(String memberCode,String code) throws ServiceRuntimeException
    {
        SysTopic sysTopic = findByCode(code);
        if(null != sysTopic)
        {
            sysTopic.setGoods(sysTopic.getGoods()+1);
            this.update(sysTopic);
        }
    }

    @Override
    public void good(String param)
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String code = jsonObject.getString("code");
        String memberCode = jsonObject.getString("memberCode");
        this.addGood(memberCode,code);
    }

    @Override
    public List<SysTopic> findTitleLike(String title)
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(0, 10, sort);
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("title", new SearchFilter("title", SearchFilter.Operator.LIKE, title));
        Specification<SysTopic> spec = DynamicSpecifications.bySearchFilter(filters.values(), SysTopic.class);
        Page<SysTopic> data = this.sysTopicDao.findAll(spec,pageRequest);
        if(null == data || data.getContent() == null || data.getContent().size() ==0)
            return null;
        return data.getContent();
    }

    @Override
    public List<SysTopic> findTagsLike(String tag)
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(0, 10, sort);
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("tags", new SearchFilter("tags", SearchFilter.Operator.LIKE, tag));
        Specification<SysTopic> spec = DynamicSpecifications.bySearchFilter(filters.values(), SysTopic.class);
        Page<SysTopic> data = this.sysTopicDao.findAll(spec,pageRequest);
        if(null == data || data.getContent() == null || data.getContent().size() ==0)
            return null;
        return data.getContent();
    }
}
